package com.canaan.business.controller.pc.bill;

import java.util.List;

import com.canaan.business.common.enums.agv.AgvEnum;
import com.canaan.business.common.enums.inOutStock.ErpBillTypeEnum;
import com.canaan.business.common.enums.inOutStock.OutOrderStatusEnum;
import com.canaan.business.common.helper.EmptyStockHelper;
import com.canaan.business.domain.basic.WmsStorehouseLocation;
import com.canaan.business.domain.bill.*;
import com.canaan.business.domain.inOutStock.OutStockBill;
import com.canaan.business.domain.storehouse.WmsStorehouseStock;
import com.canaan.business.service.agv.IAgvTaskDispatchService;
import com.canaan.business.service.basic.IWmsStorehouseLocationService;
import com.canaan.business.service.bill.*;
import com.canaan.business.service.inOutStock.IBindRecordService;
import com.canaan.business.service.inOutStock.IOutStockBillService;
import com.canaan.business.service.storehouse.IWmsStorehouseStockService;
import com.canaan.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.canaan.common.annotation.Log;
import com.canaan.common.core.controller.BaseController;
import com.canaan.common.core.domain.AjaxResult;
import com.canaan.common.enums.BusinessType;

import javax.annotation.Resource;

import com.canaan.common.utils.poi.ExcelUtil;
import com.canaan.common.core.page.TableDataInfo;

/**
 * 托盘Controller
 *
 * @author canaan
 * @date 2025-03-30
 */
@Api(tags = "托盘")
@RestController
@RequestMapping("/bill/tray")
public class TrayController extends BaseController {
    @Resource
    private ITrayService trayService;
    @Resource
    private IOutStockBillService outStockBillService;
    @Resource
    private IWmsStorehouseStockService storehouseStockService;
    @Resource
    private IAdjustOutBillService adjustOutBillService;
    @Resource
    private IModulationOutBillService modulationOutBillService;
    @Resource
    private IPurchaseReturnBillService purchaseReturnBillService;
    @Resource
    private IBindRecordService bindRecordService;

    @Resource
    private ITrayDetailService trayDetailService;
    @Resource
    private EmptyStockHelper emptyStockHelper;
    @Resource
    private IAgvTaskDispatchService agvTaskDispatchService;
    @Resource
    private IWmsStorehouseLocationService storehouseLocationService;

    /**
     * 查询托盘列表
     */
    @ApiOperation(value = "查询托盘列表")
//    @PreAuthorize("@ss.hasPermi('bill:tray:list')")
    @GetMapping("/list")
    public TableDataInfo list(Tray tray) {
        startPage();
        List<Tray> list = trayService.selectTrayList(tray);
        return getDataTable(list);
    }

    /**
     * 导出托盘列表
     */
    @ApiOperation(value = "导出托盘列表")
    @PreAuthorize("@ss.hasPermi('bill:tray:export')")
    @Log(title = "托盘", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Tray tray) {
        List<Tray> list = trayService.selectTrayList(tray);
        ExcelUtil<Tray> util = new ExcelUtil<Tray>(Tray.class);
        util.exportExcel(response, list, "托盘数据");
    }

    /**
     * 获取托盘详细信息
     */
    @ApiOperation(value = "获取托盘详细信息")
//    @PreAuthorize("@ss.hasPermi('bill:tray:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(trayService.selectTrayById(id));
    }

    /**
     * 新增托盘
     */
    @ApiOperation(value = "新增托盘")
    @PreAuthorize("@ss.hasPermi('bill:tray:add')")
    @Log(title = "托盘", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Tray tray) {
        return toAjax(trayService.insertTray(tray));
    }

    /**
     * 修改托盘
     */
    @ApiOperation(value = "修改托盘")
    @PreAuthorize("@ss.hasPermi('bill:tray:edit')")
    @Log(title = "托盘", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Tray tray) {
        return toAjax(trayService.updateTray(tray));
    }

    /**
     * 删除托盘
     */
    @ApiOperation(value = "删除托盘")
    @PreAuthorize("@ss.hasPermi('bill:tray:remove')")
    @Log(title = "托盘", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(trayService.deleteTrayByIds(ids));
    }

    /**
     * 通过tray处理最终出库
     */
    @ApiOperation(value = "最终出库")
    @Log(title = "最终出库", businessType = BusinessType.UPDATE)
    @PostMapping("/finalOutStock")
    public AjaxResult finalOutStock(@RequestBody Tray tray) {
        if (tray == null) {
            return error("托盘为空");
        }
        Tray newTray = trayService.selectTrayByTrayNo(tray.getTrayNo());
        if (newTray == null) {
            return error("托盘" + tray.getTrayNo() + "不存在");
        }
        if (StringUtils.isEmpty((newTray.getErpOutBillNo()))) {
            return error("托盘" + tray.getTrayNo() + "没有关联ERP出库单据");
        }

        OutStockBill trayQuery = new OutStockBill();
        trayQuery.setTrayNo(tray.getTrayNo());
        trayQuery.setDelFlag("0");
        List<OutStockBill> trayOutStockBillList = outStockBillService.selectOutStockBillList(trayQuery);
        if (trayOutStockBillList == null || trayOutStockBillList.size() == 0) {
            return error("托盘" + tray.getTrayNo() + "不存在出库单");
        }

        OutStockBill query = new OutStockBill();
        query.setRelOrderNo(newTray.getErpOutBillNo());
        query.setDelFlag("0");
        List<OutStockBill> allStockBills = outStockBillService.selectOutStockBillList(query);
        if (allStockBills == null || allStockBills.size() == 0) {
            return error("单据" + newTray.getErpOutBillNo() + "不存在出库单");
        }
        boolean isSplit = false;
        for (OutStockBill bill : allStockBills) {
            if (StringUtils.isNotEmpty(bill.getRemark())) {
                isSplit = true;
            }
        }
        WmsStorehouseStock wmsStorehouseStock = storehouseStockService.selectWmsStorehouseStockByTrayNo(tray.getTrayNo());
        if (!isSplit && wmsStorehouseStock == null) {
            return error("托盘号" + tray.getTrayNo() + "不存在库存数据");
        }
        handleTrayDetail(newTray, trayOutStockBillList, allStockBills, wmsStorehouseStock, isSplit);
        return toAjax(1);
    }

    /**
     * 处理托盘明细
     *
     * @param newTray              托盘
     * @param trayOutStockBillList 出库单列表
     * @param allStockBills        所有出库单列表
     * @param wmsStorehouseStock   库存
     * @param isSplit              是否分拣
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleTrayDetail(Tray newTray, List<OutStockBill> trayOutStockBillList, List<OutStockBill> allStockBills, WmsStorehouseStock wmsStorehouseStock, boolean isSplit) {
        WmsStorehouseLocation sourceLocation = storehouseLocationService.selectWmsStorehouseLocationByNo(wmsStorehouseStock.getStorehouseLocationNo());
        //清空托盘的关联单据
        newTray.setErpOutBillNo("");
        newTray.setSplitBillNo("");
        newTray.setErpInBillNo("");
        newTray.setOutBillNo("");
        newTray.setInBillNo("");
        trayService.updateTray(newTray);
        trayDetailService.deleteTrayDetailByTrayNo(newTray.getTrayNo());
        //判定ERP出库是否所有出库单完成
        int completeCount = 0;
        int splitCount = 0;
        for (OutStockBill item : allStockBills) {
            if (OutOrderStatusEnum.ACCOMPLISH.getCode().equals(item.getOrderStatus()) &&
                    "0".equals(item.getIsSplit())) {
                completeCount++;
            } else {
                splitCount++;
            }
        }
        if (completeCount == allStockBills.size() - splitCount) {
            handleErpBill(trayOutStockBillList.get(0));
        }
        //清除托盘明细
        if (!isSplit) {
            //将货架与托盘绑定关系解除
            bindRecordService.deleteBindRecordByParentNo(wmsStorehouseStock.getContainerNo());
            //将库存变更为空料架
            wmsStorehouseStock.setTrayNo("");
            wmsStorehouseStock.setStockStatus("");
            storehouseStockService.updateWmsStorehouseStock(wmsStorehouseStock);
            logger.info("集货创建AGV任务成功：{}", newTray.getTrayNo());
        }
    }

    /**
     * 处理ERP单据
     *
     * @param outStockBill 出库单
     */
    private void handleErpBill(OutStockBill outStockBill) {
        if (ErpBillTypeEnum.ADJUST_OUT.getCode().equals(outStockBill.getBillType())) {
            AdjustOutBill adjustOutBill = adjustOutBillService.selectAdjustOutBillByNo(outStockBill.getRelOrderNo());
            if (adjustOutBill == null) {
                return;
            }
            adjustOutBill.setStatus(OutOrderStatusEnum.ACCOMPLISH.getCode());
            adjustOutBillService.updateAdjustOutBill(adjustOutBill);
        } else if (ErpBillTypeEnum.MODULATION_OUT.getCode().equals(outStockBill.getBillType())) {
            ModulationOutBill modulationOutBill = modulationOutBillService.selectModulationOutBillByNo(outStockBill.getRelOrderNo());
            if (modulationOutBill == null) {
                return;
            }
            modulationOutBill.setStatus(OutOrderStatusEnum.ACCOMPLISH.getCode());
            modulationOutBillService.updateModulationOutBill(modulationOutBill);
        } else if (ErpBillTypeEnum.PURCHASE_RETURN.getCode().equals(outStockBill.getBillType())) {
            PurchaseReturnBill purchaseReturnBill = purchaseReturnBillService.selectPurchaseReturnBillByNo(outStockBill.getRelOrderNo());
            if (purchaseReturnBill == null) {
                return;
            }
            purchaseReturnBill.setStatus(OutOrderStatusEnum.ACCOMPLISH.getCode());
            purchaseReturnBillService.updatePurchaseReturnBill(purchaseReturnBill);
        }
    }

    /**
     * 通过tray处理最终出库
     */
    @ApiOperation(value = "最终处理出库")
    @Log(title = "最终出库处理", businessType = BusinessType.UPDATE)
    @PostMapping("/newFinalOutStock")
    public AjaxResult newFinalOutStock(@RequestBody Tray tray) {
        //基础判断
        if (tray == null) {
            return error("托盘为空");
        }
        Tray newTray = trayService.selectTrayByTrayNo(tray.getTrayNo());
        if (newTray == null) {
            return error("托盘" + tray.getTrayNo() + "不存在");
        }
        if (StringUtils.isEmpty((newTray.getErpOutBillNo()))) {
            return error("托盘" + tray.getTrayNo() + "没有关联ERP出库单据");
        }
        //清空托盘的关联单据
        newTray.setErpOutBillNo("");
        newTray.setSplitBillNo("");
        newTray.setErpInBillNo("");
        newTray.setOutBillNo("");
        newTray.setInBillNo("");
        trayService.updateTray(newTray);
        //清除托盘明细
        trayDetailService.deleteTrayDetailByTrayNo(newTray.getTrayNo());
        return toAjax(1);
    }
}
